package com.sun.util;

import javax.servlet.http.Part;
import java.io.*;
import java.util.UUID;


public class FileUploadUtils {

    /**
     * 文件上传
     * @param part
     * @return  返回的是头像的全名称 带UUID
     */
    public static String upload(Part part){
        //获取头像名称
        String photo = part.getSubmittedFileName();

        //创建一个文件夹的路径
        File file = new File("e://photo//");
        //判断是否创建文件夹
        if(!file.exists()){
            file.mkdirs();
        }

        //给文件名的前面添加uuid，保证了唯一性
        photo = UUID.randomUUID().toString()+photo;
        // 获取输入流和输出流
        InputStream is = null;
        OutputStream os = null;
        try {
            is = part.getInputStream();
            os = new FileOutputStream(file.getPath()+"//"+photo);
            int num  = -1;
            while((num = is.read())!=-1){
                os.write(num);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return photo;
    }
}
